package com.study.concurrent.C_ThreadSynchronizationHelperClass.d_WaitingForMultipleConcurrentEventsToComplete;

import java.util.concurrent.CountDownLatch;

/**
 * Created by 赵超 on 2017/3/25.
 * 视频会议类
 */
public class VideoConference implements Runnable {
    private final CountDownLatch countDownLatch;

    public VideoConference(int num) {
        this.countDownLatch = new CountDownLatch(num);
    }

    public void arrive(String name) {
        System.out.printf("%s 已经到达\n", name);
        countDownLatch.countDown();
        // 打印出尚未到达的与会者数目
        System.out.printf("还有 %s 人没有到达会场\n", countDownLatch.getCount());
    }

    @Override
    public void run() {
        System.out.printf("会议初始化人数：%s\n", countDownLatch.getCount());
        try {
            /**
             * 让视频会议线程等待，每到达一人，就会调用countDown()方法将CountDownLatch类的计数器减去一，
             * 当计数器数值变为0的时候，会 自动唤醒 所有因调用await()方法而进入休眠的线程，无需手动实现
             */
            countDownLatch.await();
            System.out.printf("人员到齐，开始开会...\n");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
